<template lang="pug">
  div.table-empty
    s-table(
      v-if="$route.path === '/operative/crm/clue'"
      ref="table"
      reqUrl="crm/web/leads/page"
      :column="tableObj.column"
      :filterProps="{ fields: searchField, model: pageParameter }"
      :initParameter="true"
      :callback="({parameter}) => tableCallback({ parameter: { ...parameter, curTab: 'Clue' } })"
      v-loading="loading"
    )
      .table-operator(slot="table-operator")
        upload-file(
          style="display: inline-block;margin-right: 10px"
          actionUrl="/api/crm/web/leads/importLeadsExcel"
          name="files"
          accept=".xlsx,.xls"
          :show-file-list="false"
          :headers="{ticket}"
          @beginUpload="beginUpload"
          @change="importChange"
        )
          el-button(size="large" round plain) 导入
        el-button(size="large" round plain @click="templateDown()") 模板下载
        el-button.gradientVertical(size="large" round @click="addHandle()") 新增
      template(slot="name" slot-scope="text, scope") {{text}}({{scope.relationship}})
      template(slot="birthday" slot-scope="text, scope")
        span {{text | dateFilter('YYYY/MM/DD')}}
      template(slot="month" slot-scope="text, scope")
        span {{scope.birthday | monthFilter}}
      template(slot="status" slot-scope="text, scope")
        el-tag(size="mini" :type="text | stautsFilter('type')") {{text | stautsFilter('name')}}
      template(slot="lastFollowRecord" slot-scope="text, scope")
        template(v-if="text")
          p {{text}}
          small.c_secondary 跟进时间:{{scope.lastFollowTime | dateFilter}}
        span(v-else) --
      template(slot="action" slot-scope="text, scope")
        el-link(@click="infoHandle(scope.id)" type="primary") 详情
    router-view(v-else)
    add-drawer(:visible.sync="modalObj.visible" @getList="getList")
    el-dialog(
      custom-class="importSkip"
      title="线索导入情况"
      width="840px"
      :visible="importSkip.visible"
      @close="importSkip.visible = false"
    )
      alert(type="info")
        span.mr5 导入条数：{{importSkip.count}}
        span 成功导入条数：{{importSkip.successCount}}
      template(v-if="importSkip.failData.length")
        h3.mt20 导入失败条目：
        s-table(
          :dataPops="importSkip.failData"
          :column="importSkip.column"
          :pagination="false"
          max-height="480px"
        )
</template>
<script>
import Alert from '@/components/Basic/Alert'
import { pagerMixin } from '@/mixins'
import { getToken } from '@/utils/auth'
import { column, statusList, importFailColumn } from './config'
import AddDrawer from './addDrawer'

const templateUrl = 'https://res.xxwbaby.com/public/%E7%BA%BF%E7%B4%A2%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xls'

export default {
  name: 'Clue',
  components: {
    AddDrawer,
    Alert
  },
  filters: {
    stautsFilter (val, key) {
      if (!val) {
        return key === 'name' ? '其他' : 'info'
      }
      const status = statusList.find(x => x.id === val?.toString()) || {}
      return status[key] || ''
    }
  },
  mixins: [pagerMixin],
  data () {
    return {
      ticket: getToken(),
      tableObj: {
        column
        // searchField: seachConfig(this.pageParameter || {})
      },
      modalObj: {
        id: '',
        visible: false
      },
      importSkip: {
        failData: [],
        visible: false,
        count: 0,
        successCount: 0,
        column: importFailColumn
      },
      loading: false
    }
  },
  computed: {
    searchField () {
      // const { pageParameter } = this
      return [
        {
          key: 'queryKey',
          label: '查询字段',
          type: 'select',
          // initialValue: pageParameter.queryKey || '',
          fieldProps: {
            options: [
              { id: 'name', name: '客户姓名' },
              { id: 'childName', name: '孩子姓名' },
              { id: 'mobile', name: '客户电话' },
              { id: 'monthAge', name: '月龄' }
            ],
            style: {
              width: '116px'
            }
          }
        },
        {
          key: 'queryVal',
          label: '查询内容',
          // initialValue: pageParameter.queryVal || '',
          fieldProps: {
            style: {
              width: '126px'
            }
          }
        },
        {
          key: 'status',
          label: '跟进状态',
          type: 'select',
          // initialValue: pageParameter.status || '',
          fieldProps: {
            options: statusList,
            style: {
              width: '156px'
            }
          }
        },
        {
          key: 'name',
          label: '跟进时间',
          key1: 'beginDate',
          key2: 'endDate',
          type: 'daterange',
          // initialValue: (pageParameter.beginDate && pageParameter.endDate) ? [pageParameter.beginDate, pageParameter.endDate] : null,
          fieldProps: {
            style: {
              width: '256px'
            }
          }
        }
      ]
    }
  },
  methods: {
    getList (flag = false) {
      this.$refs.table.refresh(flag)
    },
    // 新增/编辑
    addHandle (scope) {
      const { modalObj } = this
      this.modalObj = {
        id: scope?.id || '',
        visible: !modalObj.visible
      }
    },
    // 导入
    importChange (files) {
      console.log(files)
      files.forEach(file => {
        if (file.status === 'success' && file.response) {
          const { code, msg, data } = file.response
          if (code === this.$successCode) {
            const importSkipData = []
            const { skippedLeads, validCount, successCount } = data || {}
            if (skippedLeads && Array.isArray(skippedLeads)) {
              skippedLeads.map((x, index) => {
                const list = x.split(',')
                const obj = { id: index }
                for (let i = 0; i < list.length; i++) {
                  let key = ''
                  switch (i) {
                    case 0:
                      key = 'resource'
                      break
                    case 1:
                      key = 'childName'
                      break
                    case 2:
                      key = 'sex'
                      break
                    case 3:
                      key = 'birthday'
                      break
                    case 4:
                      key = 'name'
                      break
                    case 5:
                      key = 'relationship'
                      break
                    case 6:
                      key = 'phone'
                      break
                  }
                  obj[key] = list[i]
                }
                importSkipData.push(obj)
              })
              this.importSkip = {
                ...this.importSkip,
                failData: importSkipData,
                count: validCount,
                successCount: successCount,
                visible: true
              }
            } else {
              this.$message.success('导入成功')
            }
            this.getList(true)
          } else {
            this.$message.error(msg)
          }
        }
      })
      console.log('importChange')
      this.loading = false
    },
    beginUpload () {
      console.log('beginUpload')
      this.loading = true
    },
    // 模板下载
    templateDown () {
      window.open(templateUrl, '_blank')
    },
    // 跳转详情
    infoHandle (id) {
      this.$router.push({
        path: '/operative/crm/clue/info',
        query: { id }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.table-operator{
  margin-bottom: 18px
}
::v-deep{
  .tableWrapper{
    padding: 0
  }
}
</style>

